//
//  DDInvoiceAddInfoEditVC.swift
//  DingDongZP
//
//  Created by 三秒文化 on 2016/10/18.
//  Copyright © 2016年 51ledian.com. All rights reserved.
//

import UIKit
import ReactiveCocoa

class DDInvoiceAddInfoEditVC: LDBaseCustomizeVC {

    var addInvoiceInfo:LDBaseListTextField?
    var setDefaultInvoiceInfo:LDBaseSingleLineView?
    var bottomView:UIButton = {
        return UIButton.setDetailsBtn("保存", picName: nil, btnBackColor: LDGolbalColor.Green, titleColor: LDFontColor.White)!
    }()
    
    var titleLabArr = ["开票抬头","联  系  人","联系方式","所在地区","详细地址"]
    var sureTitle = "设置默认开票信息"
    
    var preModel:DDInvoiceInfoModelList?
    var sendModel:DDInvoiceInfoModelList?
    
    
    var placeDict = NSDictionary()
    var placeInfoModel:DDPlaceInfoModel?
    
    private var selProIndex = 0 {
        didSet{
            
            updatePickViewDataSource()
            pickView.pickView.reloadComponent(1)
        }
    }
    private var selCityIndex = 0 {
        
        didSet{
            
            updatePickViewDataSource()
            pickView.pickView.reloadComponent(2)
        }
    }
    private var selDistrictIndex = 0 {
        
        didSet{
            
        }
    }
    
    //省份lab
    private var placeLab:UITextField?
    
    var selProvienceArr = Array<String>()
    var selCityArr = Array<String>()
    var selDistrictArr = Array<String>()
    
    lazy var pickView:LDBaseAddressPickerView = {
    
        let viewP = LDBaseAddressPickerView()
        viewP.pickView.delegate = self
        viewP.pickView.dataSource = self
        return viewP
    }()
    
    private var invoiceState:Bool = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initUI()
        updateUI()
        requestPlaceInfo()
    }
    
    func updateUI() {
        
        if preModel != nil {
            
            let placeStr = String.init(format: "%@-%@-%@", preModel!.province,preModel!.city,preModel?.dist ?? "")
            addInvoiceInfo!.descTitleArr = [preModel!.name,preModel!.link_name,preModel!.link_mobile,placeStr,preModel!.address]           
            setDefaultInvoiceInfo!.showImgV?.selected = Int(preModel!.state) == 1 ? true :false
        } else {
            
            preModel = DDInvoiceInfoModelList.initWithProperty()
        }
    }
    
    
    //请求地区信息
    func requestPlaceInfo() {
        
        LDCheckPublicInfo.shareInstance.checkoutThridPlace { [weak self] (data) in
            
            self?.placeInfoModel = DDPlaceInfoModel.yy_modelWithDictionary(data as [NSObject : AnyObject])
            self?.updatePickViewDataSource()
        
        }
    }
    
    //pickview 显示调整
    func updatePickViewDataSource() {
        
        //provience
        selProvienceArr = (placeInfoModel?.list.map({ (dict) -> String in
            
            let str = dict["name"] as? String ?? ""
            return str
        }))!
        //city
        let cityDictArr = placeInfoModel?.list[selProIndex]["city"] as? Array<NSDictionary> ?? [NSDictionary]()
        selCityArr = cityDictArr.map({ (dict) -> String in
            
            let str = dict["name"] as? String ?? ""
            return str
        })
        //area
        selDistrictArr = cityDictArr[selCityIndex]["area"] as? Array<String> ?? [String]()
    }
    
    //初始化ui
    func initUI() {
        
        view.backgroundColor = LDGolbalColor.BgGoundGray
        
        addInvoiceInfo = LDBaseListTextField.init(listTitleArr: titleLabArr, type: .Edit)
        addInvoiceInfo?.backgroundColor = LDGolbalColor.White

        let lab = addInvoiceInfo?.descLabArr[3]
        let imgV = UIImageView(image: UIImage(named: "common_cell_arrow"))
        let tapV = UIView()
        tapV.userInteractionEnabled = true
        lab?.addSubview(imgV)
        lab?.addSubview(tapV)
        
        
        //联系方式正则
        let phoneTextF = addInvoiceInfo?.descLabArr[2]
        phoneTextF?.keyboardType = UIKeyboardType.PhonePad
        
        //init phone
        let phoneNumSignal = phoneTextF!.rac_textSignal().map { (obj) -> AnyObject! in
            
            var textStr = obj as? String ?? ""
            var rangStr:String?
            
            if textStr.characters.count >= 11 {
                
                let range = textStr.startIndex.advancedBy(11)
                rangStr = textStr.substringToIndex(range)
                phoneTextF!.text = rangStr
                
                return true
            } else if phoneTextF?.text?.isEmpty == true {
                
                return true
            } else {
                
                return LDUtils.validatePhone(textStr)
            }
        }
        
        //手机号判断
        RAC(phoneTextF,"textColor") <~ phoneNumSignal.map({ (obj) -> AnyObject! in
            
            let able = obj as? Bool
            
            if able == true {
                
                return LDFontColor.LightGray
            } else  {
                
                return LDFontColor.Red
            }
            
        })

        
        //文本框检测
//        var signalArrList = [AnyObject]()
//        for item in addInvoiceInfo!.descLabArr {
        
            
//            RACObserve(item, "text").subscribeNext({ (obj) in
//                
//                print(obj)
//                print(obj)
//            })
            
//            let signal = item.rac_textSignal().map({ (obj) -> AnyObject! in
//                let str = obj as? String ?? ""
//                
//                if str.isEmpty == true {
//                    
//                    return false
//                }
//                
//                return true
//            })
//            
//            signalArrList.append(signal)
//        }
        
//        //判断输入是否为空
//        let allsingal = RACSignal.combineLatest(signalArrList).map { (obj) -> AnyObject! in
//            
//            //5个文本框 a b c d
//            let tuple = obj as? RACTuple ?? RACTuple()
//            let aa = tuple.first as? Bool ?? false
//            let bb = tuple.second as? Bool ?? false
//            let cc = tuple.third as? Bool ?? false
//            let dd = tuple.fourth as? Bool ?? false
//            let ee = tuple.fifth as? Bool ?? false
//            
//            if aa && bb && cc && dd && ee == true {
//                
//                return true
//            } else {
//                
//                return false
//            }
//            
//        }
    
//        RAC(bottomView,"enabled") <~ allsingal.map({ (obj) -> AnyObject! in
//            
//            let able = obj as? Bool
//            
//            if able == true {
//                
//                return true
//            } else  {
//                
//                return false
//            }
//            
//        })
        
        
        imgV.snp_makeConstraints { (make) in
            
            make.centerY.equalTo(lab!)
            make.size.equalTo(CGSizeMake(10, 16))
            make.right.equalTo(-LDMargin_V*3)
        }
        
        tapV.snp_makeConstraints { (make) in
            
            make.top.left.equalTo(0)
            make.right.bottom.equalTo(0)
        }
        //选择城市
        tapV.bk_whenTapped { [weak self] in
            
            self?.pickView.show()
        }
        
        setDefaultInvoiceInfo = LDBaseSingleLineView()
        setDefaultInvoiceInfo?.title = sureTitle
        setDefaultInvoiceInfo?.backgroundColor = LDGolbalColor.White
        
        setDefaultInvoiceInfo?.showImgV?.rac_signalForControlEvents(UIControlEvents.TouchUpInside)
            .subscribeNext({ [weak self] (obj) in
            let btn = obj as! UIButton
                btn.selected = !btn.selected
                
                if btn.selected == true {
                    
                    self?.invoiceState = true
                    
                } else {
                    
                    self?.invoiceState = false
                }
            
        })
        
        placeLab = addInvoiceInfo!.descLabArr[3]
        
        pickView.sure { [weak self] in
            
            let selP = self?.selProvienceArr[self!.selProIndex] ?? "未选择"
            let selC = self?.selCityArr[self!.selCityIndex] ?? "未选择"
            let selD = self?.selDistrictArr[self!.selDistrictIndex] ?? "未选择"
            
            
            self?.preModel!.province = selP
            self?.preModel!.city = selC
            self?.preModel!.dist = selD
            
            self?.addInvoiceInfo!.descLabArr[3].text = selP + "-" + selC  + "-" + selD
            
        }
        

        bottomView.rac_signalForControlEvents(UIControlEvents.TouchUpInside).subscribeNext({ [weak self] (obj) in
            
            var strArr = Array<String>()
            for item in self!.addInvoiceInfo!.descLabArr {
                
                if item.text?.characters.count == 0 {
                    LDShowHUB.shareInstance.showErr("信息未填写完整")
                    return
                }
                
                strArr.append(item.text ?? LDNull)
            }
            
            self?.preModel!.name = strArr[0]
            
            self?.preModel!.link_name = strArr[1]
            self?.preModel?.title = strArr[1]
            
            
            self?.preModel!.link_mobile = strArr[2]
            self?.preModel!.address = strArr[4]
            
            self?.preModel!.state = self?.invoiceState
            
            let dict = self?.preModel?.yy_modelToJSONObject() as? NSDictionary ?? NSDictionary()
            let id = self?.preModel?.id ?? nil
            

            LDUserInfoNet.sharedInstance.editOrAddInvoiceBillInfo(id?.stringValue ?? nil, params: dict as? Dictionary<String, AnyObject>, succ: { (str) in
                
                LDShowHUB.shareInstance.showSucc(str)
                self?.navigationController?.popViewControllerAnimated(true)
                
            }, fail: { (err) in
                
                LDShowHUB.shareInstance.showErr(err as? String ?? "失败")
            })
            
            
        })
        
        
        layoutSubview()
        
    }

}

extension DDInvoiceAddInfoEditVC {
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        UIApplication.sharedApplication().sendAction(#selector(resignFirstResponder), to: nil, from: nil, forEvent: nil)
        self.pickView.dissmiss()
    }
    
    func layoutSubview() {
        view.addSubview(addInvoiceInfo!)
        view.addSubview(setDefaultInvoiceInfo!)
        view.addSubview(bottomView)
        
        
        addInvoiceInfo?.snp_makeConstraints(closure: { (make) in
            
            make.top.equalTo(LDFrame.TableCellMargin)//cell间距
            make.left.right.equalTo(0)
            make.height.equalTo(addInvoiceInfo!.getH())
        })
        
        setDefaultInvoiceInfo?.snp_makeConstraints(closure: { (make) in
            
            make.top.equalTo(addInvoiceInfo!.snp_bottom).offset(LDFrame.TableCellMargin)
            make.left.right.equalTo(0)
            make.height.equalTo(45)
        })
        
        bottomView.snp_makeConstraints(closure: { (make) in
            
            make.top.equalTo(setDefaultInvoiceInfo!.snp_bottom).offset(35)
            make.left.equalTo(LDMargin_V*4)
            make.right.equalTo(-LDMargin_V*4)
            make.height.equalTo(48)
        })
    }
}


extension DDInvoiceAddInfoEditVC:UIPickerViewDelegate,UIPickerViewDataSource {
    
    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 3
    }
    
    
    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        
        switch component {
        case 0:
            
            return (selProvienceArr ?? [String]()).count
            
        case 1:
            
            return (selCityArr ?? [String]()).count
        case 2:
            
            return (selDistrictArr ?? [String]()).count
            
            
        default:
            return 0
        }
    }
    
    func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        
        switch component {
        case 0:
            
            return selProvienceArr[row]
            
        case 1:
            
            return selCityArr[row]
        case 2:
            
            return selDistrictArr[row]
            
            
        default:
            
            return ""
        }
    }
    
    func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        
        switch component {
        case 0:
            
            selProIndex = row
            selCityIndex = 0
        case 1:
            
            selCityIndex = row
            selDistrictIndex = 0
        case 2:
            
            selDistrictIndex = row
            
            
        default:
            
            break
        }
    }
    
    
}
